//
//  MYCustomHttp.m
//  demo -- https使用
//
//  Created by 范名扬 on 15/7/2.
//  Copyright (c) 2015年 com.hztc. All rights reserved.
//

#import "MYCustomHttp.h"

static MYCustomHttp *pCustomHttpRequset;
@interface MYCustomHttp()
@property (nonatomic, strong)NSURLConnection   *pUrlConnection;
@property (nonatomic, strong)NSMutableData     *pBufData;
@end

@implementation MYCustomHttp

+ (instancetype)shareHttpRequest
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pCustomHttpRequset = [[MYCustomHttp alloc] init];
    });
    return pCustomHttpRequset;
}

+ (void)post:(NSString *)url
      params:(NSDictionary *)params
     success:(void(^)(id response))success
     failure:(void(^)(NSError *error))failure
{
    
}

+ (void)requestHttp:(id)request urlStr:(char *)urlStr parameters:(char *)parameters length:(int)length newQueryTradeType:(int)tradeType
{
    [[self alloc] initWithRequestHttp:request urlStr:urlStr parameters:parameters length:length newQueryTradeType:tradeType];
//    [[self shareHttpRequest] initWithRequestHttp:request urlStr:urlStr parameters:parameters length:length newQueryTradeType:tradeType];
}

- (void)initWithRequestHttp:(id)request urlStr:(char *)urlStr parameters:(char *)parameters length:(int)length newQueryTradeType:(int)tradeType
{
//    //下一个请求开始之前，清除上个请求
//    if (self.pUrlConnection) {
//        [self.pUrlConnection cancel];
//    }
//    if (self.pBufData) {
//        self.pBufData = nil;
//    }
    
    self.delegate = request;
    self.nTradeType = tradeType;
    
    self.pBufData = [[NSMutableData alloc] initWithLength:0];
   
    
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithUTF8String:urlStr]]];
    [requestM setTimeoutInterval:20];
    
    [requestM addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestM addValue:[NSString stringWithFormat:@"%d",length] forHTTPHeaderField:@"Content-Length"];
    [requestM setHTTPMethod:@"POST"];
    
    if (parameters) {
        [requestM setHTTPBody:[NSData dataWithBytes:parameters length:length]];
    }
    
    self.pUrlConnection = [[NSURLConnection alloc] initWithRequest:requestM delegate:self];
}

#pragma mark - NSURLConnectionDelegate
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];//接受任何证书
}

/*
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
    //iOS8
    static CFArrayRef certs;
    if (!certs) {
        NSData*certData =[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"srca" ofType:@"cer"]];
        if (certData) {
            
            SecCertificateRef rootcert =SecCertificateCreateWithData(kCFAllocatorDefault,CFBridgingRetain(certData));
            const void *array[1] = { rootcert };
            certs = CFArrayCreate(NULL, array, 1, &kCFTypeArrayCallBacks);
            CFRelease(rootcert);
        }
    }
    
    SecTrustRef trust = [[challenge protectionSpace] serverTrust];
    int err;
    SecTrustResultType trustResult = 0;
    err = SecTrustSetAnchorCertificates(trust, certs);
    if (err == noErr) {
        err = SecTrustEvaluate(trust,&trustResult);
    }
    CFRelease(trust);
    BOOL trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed)||(trustResult == kSecTrustResultConfirm) || (trustResult == kSecTrustResultUnspecified));
    
    if (trusted) {
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    }else{
        [challenge.sender cancelAuthenticationChallenge:challenge];
    }

}
*/

#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"response==%@",response);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.pBufData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    int totalLen = (int)self.pBufData.length;
    char *pChar = [self.pBufData bytes];
    
    void *pBuf = memset(malloc(totalLen), 0, totalLen);
    [self.pBufData getBytes:pBuf length:totalLen];
    NSLog(@"totalLen==%d   ===%s",totalLen,pChar);
    
    [self.delegate customHttp:pChar receiveLength:totalLen newQueryTradeType:self.nTradeType];
    
    self.pBufData = nil;
    free(pBuf);
    
    [self.pUrlConnection cancel];
    self.pUrlConnection = nil;
}

// 网络错误时触发
- (void)connection:(NSURLConnection *)aConn didFailWithError:(NSError *)error
{
    NSLog(@"超时==%ld＝＝%@",(long)error.code,error);
    NSString *errorStr = nil;
    if (error.code == -1001) {
        errorStr = @"网络超时";
    }else{
        errorStr = @"网络错误";
    }
    
    [self.delegate customHttp:errorStr];
}

+ (void)cancelHttpRequest
{
    MYCustomHttp *pCustomHttp = [MYCustomHttp shareHttpRequest];
    [pCustomHttp.pUrlConnection cancel];
    pCustomHttp.pUrlConnection = nil;
}

@end
